package com.ruoyi.common.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.logging.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ps 对原始图片进行分类、重命名、记录批次序号表、记录原始图片名称与重命名记录表
 */
public class ImageOrganizer {

    private static final Logger logger = Logger.getLogger(ImageOrganizer.class.getName());

    private static final String INPUT_DIR = "D:\\BaiduNetdiskDownload\\ps\\original";
    private static final String OUTPUT_DIR = "D:\\BaiduNetdiskDownload\\ps\\picedit";
    private static final String SEQUENCE_FILE = "D:\\BaiduNetdiskDownload\\ps\\sequence.xlsx";
    private static final String RECORD_FILE = "D:\\BaiduNetdiskDownload\\ps\\pic_old_new.xlsx";

    private static final Pattern CHINESE_CATEGORY_PATTERN = Pattern.compile("_(.*?)\\."); // 匹配中文二级分类

    // 分类映射：中文分类 -> [一级分类, 英文分类名]
    private static final Map<String, String[]> categoryMap = Map.ofEntries(
            Map.entry("风景", new String[]{"自然类", "landscape"}),
            Map.entry("动物", new String[]{"自然类", "animal"}),
            Map.entry("植物", new String[]{"自然类", "plant"}),
            Map.entry("天气现象", new String[]{"自然类", "climate"}),

            Map.entry("城市建筑", new String[]{"人文类", "architecture"}),
            Map.entry("街景", new String[]{"人文类", "street"}),
            Map.entry("室内场景", new String[]{"人文类", "indoor"}),
            Map.entry("艺术品", new String[]{"人文类", "artwork"}),

            Map.entry("肖像", new String[]{"人物类", "portrait"}),
            Map.entry("动作", new String[]{"人物类", "action"}),
            Map.entry("多人互动", new String[]{"人物类", "interaction"}),

            Map.entry("抽象艺术", new String[]{"创意类", "abstract"}),
            Map.entry("特效渲染", new String[]{"创意类", "render"}),

            Map.entry("产品图", new String[]{"功能类", "product"}),
            Map.entry("图表", new String[]{"功能类", "chart"}),
            Map.entry("信息图", new String[]{"功能类", "chart"}),
            Map.entry("图表_信息图", new String[]{"功能类", "chart"})
    );

    // 存储分类英文名与当前序号映射
    private static final Map<String, Integer> sequenceMap = new HashMap<>();

    // 存储记录列表
    private static final List<String[]> recordList = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        setupLogger();
        loadSequence();
        processImages();
        saveSequence();
        saveRecords();
        logger.info("✅ 所有图片处理完毕。");
    }

    /** 设置日志格式 */
    private static void setupLogger() {
        ConsoleHandler handler = new ConsoleHandler();
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.setUseParentHandlers(false);
    }

    /** 加载序号 Excel */
    private static void loadSequence() {
        File file = new File(SEQUENCE_FILE);
        if (!file.exists()) return;

        try (Workbook workbook = new XSSFWorkbook(new FileInputStream(file))) {
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                String category = row.getCell(0).getStringCellValue();
                int index = (int) row.getCell(1).getNumericCellValue();
                sequenceMap.put(category, index);
            }
            logger.info("📄 已加载序号记录。");
        } catch (Exception e) {
            logger.warning("⚠️ 加载序号失败: " + e.getMessage());
        }
    }

    /** 保存序号到 Excel */
    private static void saveSequence() {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Sequence");
            int rowNum = 0;
            for (Map.Entry<String, Integer> entry : sequenceMap.entrySet()) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(entry.getKey());
                row.createCell(1).setCellValue(entry.getValue());
            }
            try (FileOutputStream out = new FileOutputStream(SEQUENCE_FILE)) {
                workbook.write(out);
            }
            logger.info("💾 序号保存成功。");
        } catch (Exception e) {
            logger.warning("❌ 保存序号失败: " + e.getMessage());
        }
    }

    /** 保存图片重命名记录 */
    private static void saveRecords() {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Records");
            int rowNum = 0;
            for (String[] record : recordList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < record.length; i++) {
                    row.createCell(i).setCellValue(record[i]);
                }
            }
            try (FileOutputStream out = new FileOutputStream(RECORD_FILE)) {
                workbook.write(out);
            }
            logger.info("📘 图片重命名记录已保存。");
        } catch (Exception e) {
            logger.warning("❌ 保存记录失败: " + e.getMessage());
        }
    }

    /** 主流程：处理所有图片 */
    private static void processImages() throws IOException {
        Files.walk(Paths.get(INPUT_DIR))
                .filter(Files::isRegularFile)
                .filter(path -> {
                    String name = path.getFileName().toString().toLowerCase();
                    return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png");
                })
                .forEach(ImageOrganizer::processImage);
    }

    /** 处理单张图片 */
    private static void processImage(Path path) {
        String fileName = path.getFileName().toString();
        Matcher matcher = CHINESE_CATEGORY_PATTERN.matcher(fileName);
        if (!matcher.find()) {
            logger.warning("跳过：无法识别分类 - " + fileName);
            return;
        }

        String chineseCategory = matcher.group(1);
        if (!categoryMap.containsKey(chineseCategory)) {
            logger.warning("跳过：未定义分类 - " + chineseCategory);
            return;
        }

        String[] categoryInfo = categoryMap.get(chineseCategory);
        String primaryCategory = categoryInfo[0];
        String englishCategory = categoryInfo[1];

        int currentIndex = sequenceMap.getOrDefault(englishCategory, 0) + 1;
        sequenceMap.put(englishCategory, currentIndex);

        String newName = String.format("%s_%05d_original.jpg", englishCategory, currentIndex);
        Path destDir = Paths.get(OUTPUT_DIR, primaryCategory, chineseCategory);
        Path destPath = destDir.resolve(newName);

        try {
            Files.createDirectories(destDir);
            Files.move(path, destPath, StandardCopyOption.REPLACE_EXISTING);
            logger.info("✅ 重命名并保存: " + fileName + " -> " + newName);

            recordList.add(new String[]{fileName, newName, primaryCategory, chineseCategory});
        } catch (IOException e) {
            logger.warning("❌ 复制失败: " + e.getMessage());
        }
    }
}

